from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
import tempfile
import os

mcp = FastMCP("Python-dateutil MCP Server")

"""
Python-dateutil MCP Server

面向软件：python-dateutil（Python日期工具库）

MCP tools 列表：
1. dateutil_parser_test - 运行日期解析功能测试
   用途：测试dateutil的解析器功能
   参数：无
   返回：测试执行结果

2. dateutil_parse_date - 解析字符串日期
   用途：将字符串日期解析为datetime对象
   参数：date_str - 要解析的日期字符串
   返回：解析结果和执行状态

3. dateutil_calculate_date_diff - 计算日期差
   用途：计算两个日期之间的差值
   参数：start_date - 起始日期（YYYY-MM-DD格式）
         months - 增加的月数
         days - 增加的天数
   返回：计算结果和执行状态
"""

@mcp.tool()
def dateutil_parser_test() -> dict:
    """
    运行日期解析功能测试
    
    用途：执行预定义的日期解析功能测试脚本，验证dateutil解析器功能
    参数：无
    返回JSON结构：
        {
            "success": bool,      # 测试是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    try:
        # 创建临时测试文件
        test_script = """
from dateutil import parser

# 测试各种日期格式的解析
test_cases = [
    "2024-12-25",
    "2024/12/25",
    "Dec 25, 2024",
    "25 December 2024"
]

for date_str in test_cases:
    parsed_date = parser.parse(date_str)
    print(f"Original: {date_str} -> Parsed: {parsed_date}")

print("Date and time parsed successfully!")
"""
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
            f.write(test_script)
            temp_file = f.name
        
        # 执行测试
        result = subprocess.run(
            ['python3', temp_file],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        # 清理临时文件
        os.unlink(temp_file)
        
        return {
            "success": result.returncode == 0 and "Date and time parsed successfully!" in result.stdout,
            "command": f"python3 {temp_file}",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": "python3 parser_function_test.py",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def dateutil_parse_date(date_str: str) -> dict:
    """
    解析字符串日期
    
    用途：使用dateutil.parser将字符串日期解析为datetime对象
    参数：
        date_str: str - 要解析的日期字符串（如："2024-12-25"）
    返回JSON结构：
        {
            "success": bool,      # 解析是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出（包含解析结果）
            "stderr": str         # 标准错误
        }
    """
    try:
        # 创建临时Python脚本
        python_script = f"""
from dateutil import parser

date_str = "{date_str}"
try:
    parsed_date = parser.parse(date_str)
    print(f"Parsed Date: {{parsed_date}}")
    print("SUCCESS")
except Exception as e:
    print(f"ERROR: {{e}}")
"""
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
            f.write(python_script)
            temp_file = f.name
        
        # 执行Python脚本
        result = subprocess.run(
            ['python3', temp_file],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        # 清理临时文件
        os.unlink(temp_file)
        
        success = result.returncode == 0 and "SUCCESS" in result.stdout
        
        return {
            "success": success,
            "command": f"python3 {temp_file}",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": f"python3 parse_date.py (date_str: {date_str})",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def dateutil_calculate_date_diff(start_date: str, months: int = 0, days: int = 0) -> dict:
    """
    计算日期差
    
    用途：计算从起始日期增加指定月数和天数后的日期，并计算日期差
    参数：
        start_date: str - 起始日期（YYYY-MM-DD格式，如："2024-01-01"）
        months: int - 要增加的月数（默认0）
        days: int - 要增加的天数（默认0）
    返回JSON结构：
        {
            "success": bool,      # 计算是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出（包含计算结果）
            "stderr": str         # 标准错误
        }
    """
    try:
        # 解析起始日期
        year, month, day = map(int, start_date.split('-'))
        
        # 创建临时Python脚本
        python_script = f"""
from dateutil.relativedelta import relativedelta
from datetime import datetime

try:
    # 解析起始日期
    current_date = datetime({year}, {month}, {day}, 0, 0)
    
    # 计算未来日期
    future_date = current_date + relativedelta(months={months}, days={days})
    
    # 计算日期差
    date_diff = future_date - current_date
    
    print(f"Start Date: {{current_date}}")
    print(f"Future Date: {{future_date}}")
    print(f"Date Difference: {{date_diff}}")
    print("SUCCESS")
except Exception as e:
    print(f"ERROR: {{e}}")
"""
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
            f.write(python_script)
            temp_file = f.name
        
        # 执行Python脚本
        result = subprocess.run(
            ['python3', temp_file],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        # 清理临时文件
        os.unlink(temp_file)
        
        success = result.returncode == 0 and "SUCCESS" in result.stdout
        
        return {
            "success": success,
            "command": f"python3 {temp_file}",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": f"python3 calculate_date_diff.py (start_date: {start_date}, months: {months}, days: {days})",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()